package com.lq.fastnews.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.support.design.widget.NavigationView;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;

import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.GravityCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.animation.AccelerateInterpolator;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.lq.fastnews.MyApp;
import com.lq.fastnews.R;
import com.lq.fastnews.ui.fragment.HomeFragment;
import com.lq.fastnews.ui.fragment.ImageFragment;

import com.lq.fastnews.utils.Const;
import com.lq.fastnews.utils.DevicesUtil;
import com.lq.fastnews.utils.LogUtil;
import com.lq.fastnews.utils.StatusBarUtil;
import com.lq.fastnews.utils.StringUtil;
import com.lq.fastnews.utils.UIUtil;
import com.lq.fastnews.utils.XutilHelper;
import com.lq.permission_lib.PermissionsActivity;
import com.lq.permission_lib.PermissionsChecker;
import com.umeng.message.IUmengRegisterCallback;
import com.umeng.message.PushAgent;
import com.umeng.message.UmengNotificationClickHandler;
import com.umeng.message.UmengRegistrar;
import com.umeng.message.entity.UMessage;

import butterknife.Bind;
import io.codetail.animation.SupportAnimator;
import io.codetail.animation.ViewAnimationUtils;

public class MainActivity extends LoadActivity
        implements NavigationView.OnNavigationItemSelectedListener, ViewPager.OnPageChangeListener, Runnable {
    private static final int REQUEST_CODE = 1;
    @Bind(R.id.toolbar)
    Toolbar toolbar;
    @Bind(R.id.drawer_layout)
    DrawerLayout drawer;
//    @Bind(R.id.vp_content)
//    NoSlideViewPager vp_content;
    @Bind(R.id.nav_view)
    NavigationView navigationView;
    @Bind(R.id.reveal)
    View reveal;
    @Bind(R.id.fl_content)
    LinearLayout frameLayout;
    private ActionBarDrawerToggle mToggle;
    private Fragment mHomeFragment;
    private Fragment mImageFragment;
    private int mId;


    @Override
    protected void init() {
        PushAgent mPushAgent = PushAgent.getInstance(MyApp.mContext);
        mPushAgent.enable();
        setSupportActionBar(toolbar);
        setStatuAndNavigationColor(UIUtil.getColor(R.color.colorPrimary),UIUtil.getColor(android.R.color.transparent));
        toolbar.setTitle(R.string.news_home);
        mToggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.addDrawerListener(mToggle);
        mToggle.syncState();
        navigationView.setNavigationItemSelectedListener(this);
//        setViewPage();
//        selectItem(R.id.nav_home);
        FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) frameLayout.getLayoutParams();
        if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.KITKAT){
            params.topMargin=DevicesUtil.dip2px(56)+StatusBarUtil.getStatusBarHeight();
        }else {
            params.topMargin=DevicesUtil.dip2px(56);
        }
//        getSupportFragmentManager().beginTransaction().replace(R.id.fl_content,new TestFragment()).commit();

        selectItem(0);
        String device_token = UmengRegistrar.getRegistrationId(MyApp.mContext);
        LogUtil.i("device_token",device_token);
        System.out.println(device_token);
        //开启推送并设置注册的回调处理
//        mPushAgent.enable(new IUmengRegisterCallback() {
//
//            @Override
//            public void onRegistered(final String registrationId) {
////               tabHost.post(new Runnable() {
////                    @Override
////                    public void run() {
////                        //onRegistered方法的参数registrationId即是device_token
////                        LogUtil.i("device_token", registrationId);
////                    }
////                });
//            }
//        });

        /**
         * 该Handler是在BroadcastReceiver中被调用，故
         * 如果需启动Activity，需添加Intent.FLAG_ACTIVITY_NEW_TASK
         * */
        UmengNotificationClickHandler notificationClickHandler = new UmengNotificationClickHandler(){
            @Override
            public void dealWithCustomAction(Context context, UMessage msg) {
                Toast.makeText(context, msg.custom, Toast.LENGTH_LONG).show();
            }
        };
        mPushAgent.setNotificationClickHandler(notificationClickHandler);
    }

    private void setViewPage() {
        FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) frameLayout.getLayoutParams();
        if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.KITKAT){
            params.topMargin=DevicesUtil.dip2px(56)+StatusBarUtil.getStatusBarHeight();
        }else {
            params.topMargin=DevicesUtil.dip2px(56);
        }
//        vp_content.setLayoutParams(params);
//        vp_content.setAdapter(new MyAdapter(getSupportFragmentManager()));
//        vp_content.setCurrentItem(0);
//        vp_content.addOnPageChangeListener(this);
    }
//private class MyAdapter extends FragmentStatePagerAdapter {
//
//    public MyAdapter(FragmentManager fm) {
//        super(fm);
//    }
//
//    @Override
//    public Fragment getItem(int position) {
//        return  selectItem(position);
//    }
//
//    @Override
//    public int getCount() {
//        return 4;
//    }
//}
    private void setStatuAndNavigationColor(int navigationColor,int statuColor) {
        setBottomNavigationColor(navigationColor);
        StatusBarUtil.setColorNoTranslucentForDrawerLayout(this, drawer,statuColor);
    }

    public void showRevealAnim(SupportAnimator.AnimatorListener listen, boolean isShow) {
        if (isShow) {
            reveal.setVisibility(View.VISIBLE);
            int finalRadius = Math.max(DevicesUtil.getScreenWidth(), DevicesUtil.getScreenHeight()) + Math.min(DevicesUtil.getScreenWidth(), DevicesUtil.getScreenHeight()) / 2;
            SupportAnimator animator = ViewAnimationUtils.createCircularReveal(reveal, 0, 0, 0, finalRadius);

            animator.setInterpolator(new AccelerateInterpolator());
            animator.setDuration(500);
            animator.start();
            animator.addListener(listen);
        } else {
            reveal.setVisibility(View.GONE);
        }


    }



    @Override
    protected int getContentViewLayoutID() {
        return R.layout.activity_main;
    }

    @Override
    public void onBackPressed() {
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        drawer.closeDrawer(GravityCompat.START);
        mId = item.getItemId();
        XutilHelper.postDelayed(this, Const.TIME);

//        selectItem(id);


        return true;
    }
//    HashMap<Integer,Fragment> mFragments = new HashMap<>();


    /**
     * 左侧drawer选择事件
     *
     * @param position
     */
    public Fragment selectItem(int position) {


        FragmentManager fm = getSupportFragmentManager();
        FragmentTransaction transaction = fm.beginTransaction();
        hideFragment(transaction);

        switch (position) {
            case 0:
                //首页
                if(mHomeFragment==null){
                    mHomeFragment =new HomeFragment();

                    transaction.add(R.id.fl_content, mHomeFragment);
                } else{
                    transaction.show(mHomeFragment);
                }

                break;
            case 1:
                if(mImageFragment==null){
                    mImageFragment = new ImageFragment();
                    transaction.add(R.id.fl_content, mImageFragment);
                }else {
                    transaction.show(mImageFragment);
                }
//                startActivity(new Intent(this,ImageActivity.class));

                break;
            case 2:

                break;
             case 3:

                break;


            default:
                break;
        }
        transaction.commitAllowingStateLoss();
        return null;
    }
    private void hideFragment(FragmentTransaction transaction)
    {
        if (mHomeFragment != null)
        {
            transaction.hide(mHomeFragment);
        }
        if (mImageFragment != null)
        {
            transaction.hide(mImageFragment);
        }
//        if (mTab03 != null)
//        {
//            transaction.hide(mTab03);
//        }
//        if (mTab04 != null)
//        {
//            transaction.hide(mTab04);
//        }
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (drawer != null) {
            if (drawer.isDrawerOpen(GravityCompat.START)) {
                drawer.closeDrawer(GravityCompat.START);
            }
            drawer.removeDrawerListener(mToggle);
            drawer = null;
        }
//        if (vp_content != null) {
//            vp_content.removeOnPageChangeListener(this);
//            vp_content = null;
//        }
        if (reveal != null) {
            reveal.clearAnimation();
        }
        DevicesUtil.fixInputMethodManagerLeak(this);
        XutilHelper.removeCallbacks(this);
    }


    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        String title = "";
        switch (position) {
            case 0:
                title = StringUtil.getResString(R.string.news_home);
                break;
            case 1:
                title = StringUtil.getResString(R.string.look_image);
                break;
            case 2:
                title = "天气";
                break;
            case 3:
                title = "设置";
                break;
        }
        toolbar.setTitle(title);
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

    @Override
    public void run() {
        switch (mId) {
            case R.id.nav_home:
//                replace("home",id);
//                vp_content.setCurrentItem(0);
                selectItem(0);
                break;

            case R.id.nav_image:
//                replace("image",id);
//                vp_content.setCurrentItem(1);
                selectItem(1);
                break;
            case R.id.nav_weather:
//                replace("image",id);
                UIUtil.startActivity(this,WeatherActivity.class);
//                vp_content.setCurrentItem(2);
                break;

        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        // 缺少权限时, 进入权限配置页面
//        if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.M)
//        if (PermissionsChecker.lacksPermissions(MyApp.mContext,PermissionsChecker.PERMISSIONS)) {
//            ActivityCompat.requestPermissions(this, PermissionsChecker.PERMISSIONS, 0);
//        }
    }
}
